/*
 * Copyright 2010 WANdisco, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package com.googlecode.svnj.reports;

import java.io.IOException;
import java.io.OutputStream;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavResource;
import org.apache.jackrabbit.webdav.WebdavRequest;
import org.apache.jackrabbit.webdav.WebdavResponse;
import org.w3c.dom.Node;

import com.googlecode.svnj.XMLUtil;
import com.googlecode.svnj.dav.Path;
import com.googlecode.svnj.dav.SVNResource;

public class GetLocationsReport extends ReportRequest {

    /** root node of xml REPORT stanza in request body */
    private Node root;
    @Override
    public String getReportType() {
        return TYPE_GET_LOCATIONS;
    }

    @Override
    protected void parse(Node root) {
        this.root = root;
    }

    public String getPath() {
        return XMLUtil.getChildText(root, "path");
    }
    
    public long getPegRevision() {
        Long ret = XMLUtil.getChildLong(root, "peg-revision", -1l);
        return ret;
    }

    public Long getLocationRevision() {
        Long ret = XMLUtil.getChildLong(root, "location-revision", -1l);
        return ret;
    }

    public void report(WebdavRequest req, WebdavResponse rsp, DavResource resource)
    throws DavException, IOException,XMLStreamException {
        OutputStream os = rsp.getOutputStream();
        XMLStreamWriter xs = XMLUtil.initWriter(os, "S:get-locations-report");
        xs.writeEmptyElement("S:location");
        Long lr = getLocationRevision();
        if (lr != null) {
            xs.writeAttribute("rev", String.valueOf(getLocationRevision()));
        }
        SVNResource svnResource = (SVNResource) resource;
        // join the path of the request URI, with the path in the report,
        // if any
        String resourcePath = svnResource.getSpecialResource().getReposPath();
        String reportPath = getPath();
        String fullPath = Path.join(resourcePath, reportPath);
        xs.writeAttribute("path", fullPath);
        xs.writeEndElement(); // S:location
        xs.writeEndDocument();
        
    }        
}
/*
<S:get-locations xmlns:S="svn:">
 <S:path/>
 <S:peg-revision>8</S:peg-revision>
 <S:location-revision>1</S:location-revision>
</S:get-locations>
 */
